import { createRouter, createWebHashHistory, type RouteLocationNormalized } from "vue-router";
import { useCachedViewStoreHook } from "/@/store/modules/cachedView";
import { routes } from "./routes";
import { Local } from "/@/utils/storage";
import NProgress from "/@/utils/progress";

export interface toRouteType extends RouteLocationNormalized {
	meta: {
		title?: string;
		noCache?: boolean;
	};
}

// 设置页面 title
const pageDefaultTitle = "vu3-h5-template";
function setPageTitle(routerTitle?: string): void {
	window.document.title = routerTitle ? `${routerTitle} | ${pageDefaultTitle}` : `${pageDefaultTitle}`;
}

// 创建路由 router
const router = createRouter({
	history: createWebHashHistory(),
	routes,
});

// 路由加载前
router.beforeEach((to: toRouteType, from, next) => {
	NProgress.start();
	/* 关闭登录状态校验 */
	useCachedViewStoreHook().addCachedView(to); // 设置路由缓存
	setPageTitle(to.meta.title);
	next();
	/* 开启登录状态校验 */
	// const isLogin = Local.has("token") && Local.has("userInfo"); // 登录状态
	// if (!isLogin && to.path === "/login") {
	// 	next();
	// } else if (!isLogin) {
	// 	next(`/login?redirect=${to.path}&params=${JSON.stringify(to.query ? to.query : to.params)}`);
	// } else if (isLogin) {
	// 	if (to.path === "/login") {
	// 		next("/home");
	// 	} else {
	// 		useCachedViewStoreHook().addCachedView(to); // 设置路由缓存
	// 		next();
	// 	}
	// }
});

// 路由加载后
router.afterEach(() => {
	NProgress.done();
});

export default router;
